package org.light.framework.mvc;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.light.framework.HelperLoader;
import org.light.framework.ioc.BeanHelper;
import org.light.framework.util.ArrayUtil;
import org.light.framework.util.ConfigUtil;
import org.light.framework.util.EncoderUtil;
import org.light.framework.util.JsonUtil;
import org.light.framework.util.ReflectionUtil;
import org.light.framework.util.StreamHelper;
import org.light.framework.util.StringUtil;

/**
 * 请求分发器
 * @author de.cel
 *
 */
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	ThreadLocal<HttpServletRequest> REQUEST_HOLDER=new ThreadLocal<HttpServletRequest>();
	
	@Override
	public void init(ServletConfig servletConfig) {
		HelperLoader.init();

		ServletContext servletContext = servletConfig.getServletContext();

		// 注册处理JSP的Servlet
		ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
		jspServlet.addMapping("/index.jsp");
		jspServlet.addMapping(ConfigUtil.getAppJspPath() + "*");

		// 注册处理静态资源的默认Servlet
		ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
		defaultServlet.addMapping(ConfigUtil.getAppAssetPath() + "*");
	}
	
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		String requestMethod = request.getMethod().toLowerCase();
		String requestPath = request.getPathInfo();

		Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
		if (handler != null) {

			Class<?> actionClass = handler.getActionClass();
			Object controllerObj = BeanHelper.getBean(actionClass);
			Map<String, Object> requestParams = new HashMap<String, Object>();
			Enumeration<String> paramNames = request.getParameterNames();
			while (paramNames.hasMoreElements()) {
				String paramName = paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				requestParams.put(paramName, paramValue);
			}

			String body = EncoderUtil.decodeURL(StreamHelper.getString(request.getInputStream()));
			if (StringUtil.isNotNullOrEmpty(body)) {
				String[] params = StringUtil.split(body, "&");
				if (ArrayUtil.isNotEmpty(params)) {
					for (String param : params) {
						String[] array = StringUtil.split(param, "=");
						if (ArrayUtil.isNotEmpty(array) && array.length == 2) {
							String paramName = array[0];
							String paramValue = array[1];
							requestParams.put(paramName, paramValue);
						}
					}
				}
			}

			RequestParam param = new RequestParam(requestParams);
			Method actionMethod = handler.getActionMethod();
			Object result = ReflectionUtil.invokeMethod(controllerObj, actionMethod, param);
			if (result instanceof View) {
				View view = (View) result;
				String path = view.getPath();
				if (StringUtil.isNotNullOrEmpty(path)) {
					if (path.startsWith("/")) {
						response.sendRedirect(request.getContextPath() + path);
					} else {
						Map<String, Object> model = view.getModel();
						for (Map.Entry<String, Object> entry : model.entrySet()) {
							request.setAttribute(entry.getKey(), entry.getValue());
						}
						
						REQUEST_HOLDER.set(request);
						request.getRequestDispatcher(ConfigUtil.getAppJspPath() + path).forward(request, response);
					}
				}
			} else if (result instanceof Data) {
				Data data = (Data) result;
				Object model = data.getModel();
				if (model != null) {
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					PrintWriter writer=response.getWriter();
					String json=JsonUtil.toJson(model);
					writer.write(json);
					writer.flush();
					writer.close();
				}
			}
		}else{
			//super.service(request, response);
		}

	}
}
